<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\User;

use App\Constants\Constants;
use App\Dao\IntegralDetailDao;
use App\Dao\UserDao;
use App\Kernel\Util\UserJwtInstance;
use App\Service\Service;

use Hyperf\Di\Annotation\Inject;

/**
 * 积分服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\Admin
 */
class IntegralDetailService extends Service
{

    /**
     * 用户
     * @Inject
     *
     * @var UserDao
     */
    private $user_dao;

    /**
     * 积分详情
     * @Inject
     *
     * @var IntegralDetailDao
     */
    private $integral_detail_dao;

    /**
     * 用户积分明细 - 分销会员获得
     *
     * @return mixed
     */
    public function get()
    {
        $integral_detail = [];

        $integral_detail['integral_list'] = $this->integral_detail_dao->getByUserId([
            'user_id' => uid(),
            'type' => 1,
            'status' => 2,
        ]);

        $integral_detail['parent_count'] = $this->user_dao->count([
            'parent_id' => uid()
        ]);

        $integral_detail['integral_total'] = $this->getIntegralBalanceByShare( uid() );

        return $integral_detail;
    }

    /**
     * 用户积分修改
     * @param int $user_id
     * @return mixed
     */
    public function updateIntegralBalance(int $user_id)
    {
        $balance = $this->sumIntegralBalance( [
            'user_id' => $user_id,
            'type' => 1
        ] );

        $balanceShare = $this->sumIntegralBalance( [
            'user_id' => $user_id,
            'status' => 2,
            'type' => 1
        ] );

        $this->user_dao->retrieve(
            [
                'integral' => $balance
            ]
            ,
            [
                'id' => $user_id
            ]
        );

        $this->redis->hSet('txh:user:'.$user_id, 'integral', $balance);

        $this->redis->hSet('txh:user:share:'.$user_id, 'integral', $balanceShare);

        return [];
    }

    /**
     * 获取用户实时缓存积分 --- 总积分
     * @param int $user_id
     * @return string
     */
    public function getIntegralBalance(int $user_id)
    {
        $integral =  $this->redis->hGet( 'txh:user:'.$user_id, 'integral' );

        return $integral ?$integral:0;
    }

    /**
     * 获取用户实时缓存积分 --- 分润积分
     * @param int $user_id
     * @return mixed
     */
    public function getIntegralBalanceByShare(int $user_id)
    {
        $integral =  $this->redis->hGet( 'txh:user:share:'.$user_id, 'integral' );

        return $integral ?$integral:0;
    }

    /**
     * 实时计算用户积分 --- 按条件
     * @param array $map
     * @return mixed
     */
    public function sumIntegralBalance(array $map)
    {
        return $this->integral_detail_dao->sumIntegralBalance( $map );
    }
}